# -*- coding: utf-8 -*-
import hashlib
import hmac
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1852922328': {
        'API_KEY': '8af2a2840a8cf377747b9f1e2e15209d',
        'gateway': 'http://order.tdfvlp.com/gateway/',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


# weixin	微信扫码支付
# wxwap	微信wap支付
# tenpay	财付通扫码支付
# qqcode	QQ扫码支付
# qqwap	QQ钱包支付
# alipay	支付宝扫码支付
# alipaywap	支付宝WAP支付
# jdcode	京东扫码支付
# ylcode	银联扫码支付
def _get_pay_type(service):
    if service == 'alipay':
        return 'alipaywap'
    elif service == 'wxpay':
        return 'wxwap'
    elif service == 'qq':
        return 'qqwap'
    elif service == 'jd':
        return 'jdcode'
    elif service == 'quick':
        return 'ylcode'
    else:
        return 'ylcode'


def generate_sign(d, key):
    '''  生成下单签名 '''
    s = d['p0_Cmd'] + d['p1_MerId'] + d['p2_Order'] + d['p3_Amt'] + d['p4_Cur'] + d['p5_Pid'] \
        + d['p6_Pcat'] + d['p7_Pdesc'] + d['p8_Url'] + d['pa_MP'] + d['pd_FrpId'] + d['pr_NeedResponse']
    return hmac.new(key, s, hashlib.md5).hexdigest()


def generate_notify_sign(d, key):
    '''  生成下单签名 '''
    s = d['p1_MerId'] + d['r0_Cmd'] + d['r1_Code'] + d['r2_TrxId'] + d['r3_Amt'] + d['r4_Cur'] \
        + d['r5_Order'] + d['r6_Type']
    return hmac.new(key, s, hashlib.md5).hexdigest()


def verify_notify_sign(params, key):
    sign = params['hmac']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("tongdapay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('p0_Cmd', 'Buy'),
        ('p1_MerId', app_id),
        ('p2_Order', str(pay.id)),
        ('p3_Amt', '%.2f' % pay_amount),
        ('p4_Cur', 'CNY'),
        ('p5_Pid', 'charge'),
        ('p6_Pcat', 'charge'),
        ('p7_Pdesc', 'charge'),
        ('p8_Url', '{}/pay/api/{}/tongdapay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('pa_MP', 'charge'),
        ('pd_FrpId', _get_pay_type(service)),
        ('pr_NeedResponse', '1'),
    ))
    parameter_dict['hmac'] = generate_sign(parameter_dict, api_key)
    gateway = _get_gateway(app_id)
    _LOGGER.info("tongdapay create  data: %s, url: %s", parameter_dict, gateway)
    html_text = _build_form(parameter_dict, gateway)
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("tongdapay notify data1: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['r5_Order']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('tongdapay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['r1_Code'])
    trade_no = data['r2_TrxId']
    total_fee = float(data['r3_Amt'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1':
        _LOGGER.info('tongdapay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pass
    # pay_id = pay_order.id
    # api_key = _get_api_key(app_id)
    # parameter_dict = OrderedDict((
    #     ('payKey', app_id),
    #     ('outTradeNo', str(pay_id)),
    # ))
    # parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    # _LOGGER.info("tongdapay query  data: %s", parameter_dict)
    # headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    # response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    # _LOGGER.info("tongdapay query  rsp data: %s", response.text)
    # if response.status_code == 200:
    #     data = json.loads(response.text)
    #     trade_status = str(data['orderStatus'])
    #     trade_no = data['trxNo']
    #     total_fee = float(data['orderPrice'])
    #
    #     extend = {
    #         'trade_status': trade_status,
    #         'trade_no': trade_no,
    #         'total_fee': total_fee
    #     }
    #
    #     if trade_status == 'SUCCESS' or trade_status == 'FINISH':
    #         _LOGGER.info('tongdapay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
    #         order_db.add_pay_success(pay_order.mch_id, pay_order.id,
    #                                  total_fee, trade_no, extend)
    #         async_job.notify_mch(pay_order.id)
    # else:
    #     _LOGGER.warn('tongdapay data error, status_code: %s', response.status_code)
